package com.hacker.spider.wallhaven;

import java.util.List;

import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.hacker.spider.ISpider;
import com.hacker.spider.concurrent.ResultActuator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class WallHavenSpider implements ISpider {

  List<String> urlTask = Lists.newArrayList(
    "https://wallhaven.cc/search?q=Alita&categories=110&purity=100&atleast=2560x1440&sorting=relevance&order=desc");

  //  List<String> urlTask = Lists.newArrayList(
  //    "https://wallhaven.cc/search?q=view&categories=100&purity=100&atleast=2560x1440&sorting=relevance&order=desc",
  //    "https://wallhaven.cc/search?q=Alita&categories=110&purity=100&atleast=2560x1440&sorting=relevance&order=desc",
  //    "https://wallhaven.cc/search?categories=100&purity=100&atleast=2560x1440&ratios=16x9%2C16x10&topRange=1y&sorting=toplist&order=desc",
  //  "https://wallhaven.cc/search?q=Game%20of%20Thrones&categories=110&purity=100&atleast=2560x1440&sorting=relevance&order=desc"
  //  "https://wallhaven.cc/search?q=Marvel&categories=110&purity=100&atleast=2560x1440&sorting=relevance&order=desc",
  //    "https://wallhaven.cc/search?q=Iron%20Man&categories=110&purity=100&atleast=2560x1440&ratios=16x9&sorting=relevance&order=desc");

  @Override public void run() {
    urlTask.forEach(this::buildTask);
  }

  void buildTask(String url) {
    try {
      getLogger().debug("begin build task for url {}", url);
      Document document = Jsoup.connect(url).get();
      Element thumbs = document.getElementById("thumbs");
      Element paginationInfo = thumbs.selectFirst("ul.pagination");
      PageInfo pageInfo;
      if (paginationInfo != null) {
        String pageInfoJson = paginationInfo.attr("data-pagination");
        pageInfo = new ObjectMapper().configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
          .readValue(pageInfoJson, PageInfo.class);
      } else {
        pageInfo = new PageInfo(1, url);
      }
      pageInfo.buildPages().parallelStream().forEach(var -> ResultActuator.getInstance()
        .addTask(new WallHavenTask(var.getLeft(), new WallHavenHandler(var.getRight()))));
    } catch (Throwable e) {
      getLogger().error("{} build task for url {} fail, reason: {} retry.", Thread.currentThread().getName(), url,
        e.getMessage());
      buildTask(url);
    }
  }
}
